package com.lfy.fyadmin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lfy.fyadmin.common.R;
import com.lfy.fyadmin.entity.User;
import com.lfy.fyadmin.service.UserService;
import com.lfy.fyadmin.vo.UserVO;
import com.lfy.fyadmin.dto.UserUpdateRequest;
import com.lfy.fyadmin.dto.UserQueryRequest;
import com.lfy.fyadmin.dto.CurrentUserPasswordChangeRequest;
import com.lfy.fyadmin.dto.AdminResetPasswordRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
@Tag(name = "用户管理", description = "用户相关接口")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    @Operation(summary = "新增用户")
    public R<Boolean> save(@RequestBody User user) {
        boolean result = userService.save(user);
        return result ? R.ok(true) : R.fail("新增失败");
    }

    @PutMapping
    @Operation(summary = "修改用户")
    public R<Boolean> update(@RequestBody User user) {
        boolean result = userService.updateSelective(user);
        return result ? R.ok(true) : R.fail("修改失败");
    }

    @RequestMapping ("/with-relations")
    @Operation(summary = "修改/添加用户及其角色分组关联关系")
    public R<Boolean> updateWithRelations(@RequestBody UserUpdateRequest request) {
        boolean result = userService.updateUserWithRolesAndGroups(request);
        return result ? R.ok(true) : R.fail("修改失败");
    }

    @PutMapping("/change-my-password")
    @Operation(summary = "修改当前用户密码")
    public R<Boolean> changeMyPassword(@Valid @RequestBody CurrentUserPasswordChangeRequest request) {
        try {
            boolean result = userService.changeCurrentUserPassword(request);
            return result ? R.ok(true) : R.fail("密码修改失败");
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail("系统错误，请稍后重试");
        }
    }

    @PutMapping("/admin/reset-password")
    @Operation(summary = "管理员重置用户密码")
    public R<Boolean> adminResetPassword(@Valid @RequestBody AdminResetPasswordRequest request) {
        try {
            boolean result = userService.adminResetPassword(request);
            return result ? R.ok(true) : R.fail("密码重置失败");
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail("系统错误，请稍后重试");
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户")
    public R<Boolean> delete(@PathVariable Long id) {
        try {
            boolean result = userService.deleteUserWithRelations(id);
            return result ? R.ok(true) : R.fail("删除失败");
        } catch (Exception e) {
            return R.fail("删除失败：" + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询用户")
    public R<UserVO> getById(@PathVariable Long id) {
        UserVO userVO = userService.getUserWithRolesAndGroups(id);
        return userVO != null ? R.ok(userVO) : R.fail("未找到用户");
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询用户")
    public R<IPage<User>> findPage(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize,
                                   @RequestParam(required = false) String keyword,
                                   @RequestParam(required = false) Integer status,
                                   @RequestParam(required = false) Long roleId) {
        UserQueryRequest request = new UserQueryRequest();
        request.setPageNum(pageNum);
        request.setPageSize(pageSize);
        request.setKeyword(keyword);
        request.setStatus(status);
        request.setRoleId(roleId);
        
        return R.ok(userService.pageUsers(request));
    }
}